package com.qf.controller;

import com.qf.aop.annocation.FormToken;
import com.qf.aop.annocation.LoginUser;
import com.qf.aop.annocation.OrderDataSoruce;
import com.qf.common.ResultEntity;
import com.qf.entity.*;
import com.qf.feign.api.AddressService;
import com.qf.feign.api.CarService;
import com.qf.feign.api.StockService;
import com.qf.feign.api.TokenService;
import com.qf.service.IOrderService;
import com.qf.thread.pool.ShopThreadPool;
import com.qf.vo.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/orderController")
@Slf4j
public class OrderController {

    public static void main(String[] args) {

        Integer age = 10;
        Integer age2 = 10;

        Integer age3 = 133;
        Integer age4 = 133;


        System.out.println(age == age2);
        System.out.println(age3 == age4);
    }

    @Autowired
    private AddressService addressService;

    @Autowired
    private CarService carService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private StockService stockService;

    @RequestMapping("/cancelOrder/{oid}")
    @ResponseBody
    @LoginUser
    public ResultEntity cancelOrder(User user, @PathVariable String oid) {
        if (user == null) {
            return ResultEntity.error("你还没有登录，请先登录");
        }

        // 跟新订单的状态为已取消
        orderService.updateOrderStatus(oid, 3);

        // 释放库存
        stockService.unlockGoodsStock(oid);

        return ResultEntity.success();
    }


    @RequestMapping("/createOrder")
    @OrderDataSoruce
    @FormToken
    @LoginUser
    public String createOrder(User user, OrderInfo orderInfo) {
        if (user == null) {
            return "redirect:http://localhost/shop-sso/toLoginPage";
        }
        // 1.生成订单
        Order order = orderService.createOrder(user, orderInfo);

        // 2.发送消息给MQ，开启订单的倒计时
        rabbitTemplate.convertAndSend("shop-order-exhcange", "order.create", order);

        if (1 == order.getPayType()) {

        } else if (2 == order.getPayType()) {
//            return "redirect:http://localhost/shop-pay/weiXinPayController/unifiedOrder/" + order.getId();
        }

        // 2.跳转到支付模块
        return "redirect:http://localhost/shop-pay/weiXinPayController/unifiedOrder/" + order.getId();
    }


    @GetMapping("/toOrderInfoPage.html")
    @LoginUser
    public String toOrderInfoPage(User user, ModelMap modelMap) throws ExecutionException, InterruptedException {


//        Class<?> Drclass = Class.forName("com.mysql.jdbc.Driver");

        // 0、判断用户是否登录
        if (user == null) {
            return "redirect:http://localhost/shop-sso/toLoginPage";
        }

        // 异步查询用户的地址
        CompletableFuture<List<Address>> addressFuture = CompletableFuture.supplyAsync(() -> {
            return addressService.getAddressListByUid(user.getId());
        }, ShopThreadPool.executors());

        // 异步查询用户的购物车
        CompletableFuture<List<Car>> carListFuture = CompletableFuture.supplyAsync(() -> {
            return carService.getCarListByUid(user.getId());
        }, ShopThreadPool.executors());

        // 3.异步结算购物车的价格
        CompletableFuture<BigDecimal> carPriceFuture = carListFuture.thenApplyAsync((carList) -> {
            // 3.计算总价
            BigDecimal totalPrice = new BigDecimal(0.0);
            for (Car car : carList) {
                totalPrice = totalPrice.add(car.getSubTotal());
            }
            return totalPrice;
        }, ShopThreadPool.executors());


        // 阻塞等待上面三个线程全部执行完成后才返回
        CompletableFuture.allOf(addressFuture, carPriceFuture).get();

        modelMap.put("carlist", carListFuture.get());
        modelMap.put("addressList", addressFuture.get());
        modelMap.put("totalPrice", carPriceFuture.get());

        return "orderInfo";
    }

    @ResponseBody
    @RequestMapping("/getOrderById/{oid}")
    public Order getOrderById(@PathVariable String oid) {
        return orderService.getOrderById(oid);
    }


    @RequestMapping("/updateOrderStatus")
    @ResponseBody
    void updateOrderStatus(String oid, Integer status) {
        orderService.updateOrderStatus(oid, status);
    }


    @RequestMapping("/getUserOrderList")
    @LoginUser
    public String getUserOrderList(User user, ModelMap modelMap) {
        if (user == null) {
            return "redirect:http://localhost/shop-sso/toLoginPage";
        }

        // 1.查询用户的订单
        List<Order> userOrderList = orderService.getUserOrderList(user);
        modelMap.put("orderList", userOrderList);


        return "userOrderList";
    }
}
